import sys
import os
from typing import Dict, List, Optional, Tuple
from datetime import datetime, timedelta
import statistics
from .DataModels import QuestionDifficultyMetrics
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import BasicTools.DataCollectionTools as DCTools
import BasicTools.BehaviorAnalysisTools as BATools
class QuestionEvaluator:
    def __init__(self, headers: dict = None):
        self.headers = headers
        self.question_metrics: Dict[str, QuestionDifficultyMetrics] = {}
        self.user_cache: Dict[str, Dict] = {}
        # 难度分级标准
        self.difficulty_thresholds = {
            "Easy": (0, 40),
            "Medium": (40, 60),
            "Hard": (60, 80),
            "Expert": (80, 100)
        }
    def calculate_question_difficulty(self, question_id: str) -> QuestionDifficultyMetrics:
        """
        计算题目难度指标
        Args:
            question_id (str): 题目ID
        Returns:
            QuestionDifficultyMetrics: 题目难度指标
        """
        if question_id in self.question_metrics:
            return self.question_metrics[question_id]
        metrics = QuestionDifficultyMetrics(question_id=question_id)
        # 获取通过率
        try:
            metrics.pass_rate = BATools.get_question_pass_rate(question_id, self.headers)
        except Exception as e:
            print(f"获取题目 {question_id} 通过率失败: {e}")
            metrics.pass_rate = 0.5  # 默认值
        # 获取所有用户信息
        try:
            user_info = DCTools.get_user_information(headers=self.headers)
            user_ids = [user.get("user_id") for user in user_info if user.get("user_id")]
        except Exception as e:
            print(f"获取用户信息失败: {e}")
            user_ids = []
        # 分析用户表现数据
        user_performance_data = self.analyze_user_performance(question_id, user_ids)
        # 计算统计指标
        metrics.average_attempts = user_performance_data["average_attempts"]
        metrics.average_resolution_time = user_performance_data["average_resolution_time"]
        metrics.attempt_distribution = user_performance_data["attempt_distribution"]
        metrics.completion_rate = user_performance_data["completion_rate"]
        # 计算综合难度分数
        metrics.difficulty_score = self.calculate_difficulty_score(metrics)
        metrics.difficulty_level = self.classify_difficulty_level(metrics.difficulty_score)
        # 分析题目特征
        metrics.question_features = self.analyze_question_features(question_id, user_performance_data)
        self.question_metrics[question_id] = metrics
        return metrics
    def analyze_user_performance(self, question_id: str, user_ids: List[str]) -> Dict:
        """
        分析用户在特定题目上的表现
        Args:
            question_id (str): 题目ID
            user_ids (List[str]): 用户ID列表
        Returns:
            Dict: 用户表现统计数据
        """
        total_attempts = 0
        resolution_times = []
        attempt_counts = []
        users_attempted = 0
        users_completed = 0
        for user_id in user_ids:
            try:
                # 获取用户对该题目的尝试次数
                attempts = BATools.get_question_attempt_count(user_id, question_id, self.headers)
                if attempts > 0:
                    users_attempted += 1
                    total_attempts += attempts
                    attempt_counts.append(attempts)
                    # 检查是否AC
                    ac_status = BATools.get_question_ac_status(user_id, question_id, self.headers)
                    if ac_status.get("is_ac", False):
                        users_completed += 1
                        # 获取解题时间
                        resolution_info = BATools.get_question_resolution_time(user_id, question_id, self.headers)
                        if resolution_info and resolution_info.get("resolution_time"):
                            resolution_times.append(resolution_info["resolution_time"])
            except Exception as e:
                print(f"分析用户 {user_id} 在题目 {question_id} 上的表现失败: {e}")
                continue
        # 计算统计指标
        average_attempts = total_attempts / users_attempted if users_attempted > 0 else 0
        completion_rate = users_completed / users_attempted if users_attempted > 0 else 0
        # 计算平均解题时间
        if resolution_times:
            average_resolution_time = sum(resolution_times, timedelta()) / len(resolution_times)
        else:
            average_resolution_time = timedelta()
        # 分析尝试次数分布
        attempt_distribution = self.calculate_attempt_distribution(attempt_counts)
        return {
            "users_attempted": users_attempted,
            "users_completed": users_completed,
            "total_attempts": total_attempts,
            "average_attempts": average_attempts,
            "completion_rate": completion_rate,
            "average_resolution_time": average_resolution_time,
            "attempt_distribution": attempt_distribution,
            "resolution_times": resolution_times
        }
    def calculate_attempt_distribution(self, attempt_counts: List[int]) -> Dict:
        """
        计算尝试次数分布
        Args:
            attempt_counts (List[int]): 尝试次数列表
        Returns:
            Dict: 尝试次数分布统计
        """
        if not attempt_counts:
            return {"1": 0, "2-3": 0, "4-5": 0, "6+": 0}
        distribution = {"1": 0, "2-3": 0, "4-5": 0, "6+": 0}
        for count in attempt_counts:
            if count == 1:
                distribution["1"] += 1
            elif 2 <= count <= 3:
                distribution["2-3"] += 1
            elif 4 <= count <= 5:
                distribution["4-5"] += 1
            else:
                distribution["6+"] += 1
        # 转换为百分比
        total = len(attempt_counts)
        for key in distribution:
            distribution[key] = (distribution[key] / total) * 100
        return distribution
    def calculate_difficulty_score(self, metrics: QuestionDifficultyMetrics) -> float:
        """
        计算难度分数
        Args:
            metrics (QuestionDifficultyMetrics): 题目指标
        Returns:
            float: 难度分数 (0-100)
        """
        # 基于通过率的难度分数 (通过率越低，难度越高)
        pass_rate_score = (1 - metrics.pass_rate) * 50
        # 基于平均尝试次数的难度分数
        if metrics.average_attempts > 0:
            # 尝试次数越多，难度越高
            attempts_score = min(30, (metrics.average_attempts - 1) * 8)
        else:
            attempts_score = 0
        # 基于完成率的难度分数
        completion_rate_score = (1 - metrics.completion_rate) * 20
        total_score = pass_rate_score + attempts_score + completion_rate_score
        return min(100, max(0, total_score))
    def classify_difficulty_level(self, difficulty_score: float) -> str:
        """
        根据难度分数分类难度等级
        Args:
            difficulty_score (float): 难度分数
        Returns:
            str: 难度等级
        """
        for level, (min_score, max_score) in self.difficulty_thresholds.items():
            if min_score <= difficulty_score < max_score:
                return level
        return "Expert"  # 默认为最高难度
    def analyze_question_features(self, question_id: str, performance_data: Dict) -> Dict:
        """
        分析题目特征
        Args:
            question_id (str): 题目ID
            performance_data (Dict): 用户表现数据
        Returns:
            Dict: 题目特征分析
        """
        features = {
            "accessibility": "Medium",  # 题目可接近性
            "complexity": "Medium",     # 题目复杂度
            "learning_curve": "Medium", # 学习曲线陡峭程度
            "skill_requirements": [],   # 技能要求
            "common_mistakes": [],      # 常见错误
            "time_pressure": "Medium"   # 时间压力
        }
        # 分析可接近性（基于尝试人数）
        if performance_data["users_attempted"] > 0:
            if performance_data["users_attempted"] >= 20:
                features["accessibility"] = "High"
            elif performance_data["users_attempted"] >= 10:
                features["accessibility"] = "Medium"
            else:
                features["accessibility"] = "Low"
        # 分析复杂度（基于尝试次数分布）
        attempt_dist = performance_data["attempt_distribution"]
        if attempt_dist["1"] > 60:
            features["complexity"] = "Low"
        elif attempt_dist["6+"] > 20:
            features["complexity"] = "High"
        else:
            features["complexity"] = "Medium"
        # 分析学习曲线（基于平均尝试次数）
        if performance_data["average_attempts"] > 5:
            features["learning_curve"] = "Steep"
        elif performance_data["average_attempts"] < 2:
            features["learning_curve"] = "Gentle"
        else:
            features["learning_curve"] = "Moderate"
        # 分析时间压力（基于解题时间分布）
        resolution_times = performance_data["resolution_times"]
        if resolution_times:
            time_minutes = [t.total_seconds() / 60 for t in resolution_times]
            avg_time = statistics.mean(time_minutes)
            if avg_time < 30:
                features["time_pressure"] = "Low"
            elif avg_time > 120:
                features["time_pressure"] = "High"
            else:
                features["time_pressure"] = "Medium"
        return features
    def get_question_analysis_report(self, question_id: str) -> Dict:
        """
        获取题目分析报告
        Args:
            question_id (str): 题目ID
        Returns:
            Dict: 题目分析报告
        """
        if question_id not in self.question_metrics:
            self.calculate_question_difficulty(question_id)
        metrics = self.question_metrics[question_id]
        return {
            "question_id": question_id,
            "difficulty_assessment": {
                "difficulty_level": metrics.difficulty_level,
                "difficulty_score": round(metrics.difficulty_score, 2),
                "pass_rate": round(metrics.pass_rate * 100, 2),
                "completion_rate": round(metrics.completion_rate * 100, 2)
            },
            "performance_statistics": {
                "average_attempts": round(metrics.average_attempts, 2),
                "average_resolution_time": str(metrics.average_resolution_time),
                "attempt_distribution": {
                    k: round(v, 1) for k, v in metrics.attempt_distribution.items()
                }
            },
            "question_features": metrics.question_features,
            "recommendations": self.generate_question_recommendations(metrics),
            "suitable_for": self.determine_suitable_audience(metrics)
        }
    def generate_question_recommendations(self, metrics: QuestionDifficultyMetrics) -> List[str]:
        """
        生成题目改进建议
        Args:
            metrics (QuestionDifficultyMetrics): 题目指标
        Returns:
            List[str]: 改进建议列表
        """
        recommendations = []
        # 基于通过率的建议
        if metrics.pass_rate < 0.1:
            recommendations.append("题目可能过于困难，建议增加提示或降低复杂度")
        elif metrics.pass_rate > 0.9:
            recommendations.append("题目可能过于简单，建议增加挑战性")
        # 基于尝试次数的建议
        if metrics.average_attempts > 8:
            recommendations.append("用户需要多次尝试才能解决，建议提供更清晰的题目描述")
        elif metrics.average_attempts < 1.5:
            recommendations.append("大多数用户能够快速解决，可以考虑增加难度变化")
        # 基于完成率的建议
        if metrics.completion_rate < 0.3:
            recommendations.append("完成率较低，建议检查题目是否有歧义或技术问题")
        # 基于题目特征的建议
        features = metrics.question_features
        if features["accessibility"] == "Low":
            recommendations.append("题目参与度较低，建议增加题目吸引力或调整难度")
        if features["learning_curve"] == "Steep":
            recommendations.append("学习曲线陡峭，建议提供更多学习资源或分步指导")
        return recommendations
    def determine_suitable_audience(self, metrics: QuestionDifficultyMetrics) -> Dict:
        """
        确定题目适合的受众
        Args:
            metrics (QuestionDifficultyMetrics): 题目指标
        Returns:
            Dict: 适合的受众信息
        """
        audience = {
            "primary_audience": "Intermediate",
            "secondary_audience": [],
            "skill_level": "Medium",
            "experience_required": "Some experience",
            "learning_objectives": []
        }
        # 根据难度等级确定主要受众
        if metrics.difficulty_level == "Easy":
            audience["primary_audience"] = "Beginner"
            audience["skill_level"] = "Low"
            audience["experience_required"] = "No prior experience"
            audience["learning_objectives"] = ["Basic concepts", "Foundation skills"]
        elif metrics.difficulty_level == "Medium":
            audience["primary_audience"] = "Intermediate"
            audience["secondary_audience"] = ["Beginner", "Advanced"]
            audience["skill_level"] = "Medium"
            audience["experience_required"] = "Some experience"
            audience["learning_objectives"] = ["Practical application", "Problem solving"]
        elif metrics.difficulty_level == "Hard":
            audience["primary_audience"] = "Advanced"
            audience["secondary_audience"] = ["Intermediate"]
            audience["skill_level"] = "High"
            audience["experience_required"] = "Significant experience"
            audience["learning_objectives"] = ["Advanced techniques", "Complex problem solving"]
        else:  # Expert
            audience["primary_audience"] = "Expert"
            audience["skill_level"] = "Very High"
            audience["experience_required"] = "Extensive experience"
            audience["learning_objectives"] = ["Cutting-edge techniques", "Research-level problems"]
        return audience
    def get_difficulty_distribution(self, question_ids: List[str] = None) -> Dict:
        """
        获取题目难度分布
        Args:
            question_ids (List[str], optional): 题目ID列表，如果为None则分析所有题目
        Returns:
            Dict: 难度分布统计
        """
        if question_ids is None:
            # 获取所有题目
            try:
                all_questions = DCTools.get_question_list(headers=self.headers)
                question_ids = [q.get("question_id") for q in all_questions if q.get("question_id")]
            except Exception as e:
                print(f"获取题目列表失败: {e}")
                return {}
        distribution = {"Easy": 0, "Medium": 0, "Hard": 0, "Expert": 0}
        difficulty_scores = []
        for question_id in question_ids:
            if question_id not in self.question_metrics:
                self.calculate_question_difficulty(question_id)
            metrics = self.question_metrics[question_id]
            distribution[metrics.difficulty_level] += 1
            difficulty_scores.append(metrics.difficulty_score)
        total_questions = len(question_ids)
        if total_questions == 0:
            return distribution
        # 转换为百分比
        percentage_distribution = {
            level: (count / total_questions) * 100 
            for level, count in distribution.items()
        }
        # 计算统计信息
        statistics_info = {
            "total_questions": total_questions,
            "average_difficulty": statistics.mean(difficulty_scores) if difficulty_scores else 0,
            "median_difficulty": statistics.median(difficulty_scores) if difficulty_scores else 0,
            "difficulty_std": statistics.stdev(difficulty_scores) if len(difficulty_scores) > 1 else 0
        }
        return {
            "distribution": distribution,
            "percentage_distribution": percentage_distribution,
            "statistics": statistics_info,
            "difficulty_balance": self.assess_difficulty_balance(percentage_distribution)
        }
    def assess_difficulty_balance(self, percentage_distribution: Dict) -> Dict:
        """
        评估难度平衡性
        Args:
            percentage_distribution (Dict): 难度百分比分布
        Returns:
            Dict: 平衡性评估
        """
        # 理想分布（可调整）
        ideal_distribution = {
            "Easy": 30,
            "Medium": 40,
            "Hard": 20,
            "Expert": 10
        }
        balance_score = 0
        deviations = {}
        for level, ideal_pct in ideal_distribution.items():
            actual_pct = percentage_distribution.get(level, 0)
            deviation = abs(actual_pct - ideal_pct)
            deviations[level] = deviation
            balance_score += max(0, 100 - deviation * 2)  # 惩罚偏差
        balance_score /= len(ideal_distribution)
        # 生成平衡性建议
        recommendations = []
        for level, deviation in deviations.items():
            if deviation > 10:
                actual_pct = percentage_distribution[level]
                ideal_pct = ideal_distribution[level]
                if actual_pct > ideal_pct:
                    recommendations.append(f"{level}难度题目过多，建议减少{deviation:.1f}%")
                else:
                    recommendations.append(f"{level}难度题目过少，建议增加{deviation:.1f}%")
        return {
            "balance_score": round(balance_score, 2),
            "deviations": deviations,
            "recommendations": recommendations,
            "overall_assessment": self.get_balance_assessment(balance_score)
        }
    def get_balance_assessment(self, balance_score: float) -> str:
        """获取平衡性评估等级"""
        if balance_score >= 85:
            return "优秀"
        elif balance_score >= 70:
            return "良好"
        elif balance_score >= 55:
            return "一般"
        else:
            return "需要改进"
    def recommend_questions_for_user(self, user_id: str, num_recommendations: int = 5) -> List[Dict]:
        """
        为用户推荐题目
        Args:
            user_id (str): 用户ID
            num_recommendations (int): 推荐数量
        Returns:
            List[Dict]: 推荐题目列表
        """
        try:
            # 获取用户已解决的题目
            solved_questions = set()
            question_list = DCTools.get_question_list(params={"user_id": user_id}, headers=self.headers)
            for question in question_list:
                question_id = question.get("question_id")
                if question_id:
                    ac_status = BATools.get_question_ac_status(user_id, question_id, self.headers)
                    if ac_status.get("is_ac", False):
                        solved_questions.add(question_id)
            # 获取所有题目
            all_questions = DCTools.get_question_list(headers=self.headers)
            all_question_ids = [q.get("question_id") for q in all_questions if q.get("question_id")]
            # 未解决的题目
            unsolved_questions = [qid for qid in all_question_ids if qid not in solved_questions]
            # 分析用户能力水平
            user_level = self.assess_user_level(user_id, list(solved_questions))
            # 筛选合适的题目
            suitable_questions = []
            for question_id in unsolved_questions:
                if question_id not in self.question_metrics:
                    self.calculate_question_difficulty(question_id)
                metrics = self.question_metrics[question_id]
                suitability_score = self.calculate_question_suitability(user_level, metrics)
                if suitability_score > 0:
                    suitable_questions.append({
                        "question_id": question_id,
                        "difficulty_level": metrics.difficulty_level,
                        "difficulty_score": metrics.difficulty_score,
                        "suitability_score": suitability_score,
                        "pass_rate": metrics.pass_rate,
                        "features": metrics.question_features
                    })
            # 按适合度排序并返回推荐
            suitable_questions.sort(key=lambda x: x["suitability_score"], reverse=True)
            recommendations = []
            for question in suitable_questions[:num_recommendations]:
                recommendations.append({
                    "question_id": question["question_id"],
                    "difficulty_level": question["difficulty_level"],
                    "difficulty_score": round(question["difficulty_score"], 2),
                    "suitability_score": round(question["suitability_score"], 2),
                    "pass_rate": round(question["pass_rate"] * 100, 2),
                    "recommendation_reason": self.generate_recommendation_reason(
                        user_level, question
                    )
                })
            return recommendations
        except Exception as e:
            print(f"为用户 {user_id} 推荐题目失败: {e}")
            return []
    def assess_user_level(self, user_id: str, solved_questions: List[str]) -> Dict:
        """
        评估用户能力水平
        Args:
            user_id (str): 用户ID
            solved_questions (List[str]): 已解决题目列表
        Returns:
            Dict: 用户能力水平评估
        """
        if not solved_questions:
            return {
                "overall_level": "Beginner",
                "difficulty_experience": {"Easy": 0, "Medium": 0, "Hard": 0, "Expert": 0},
                "strength_areas": [],
                "growth_areas": ["Basic problem solving"]
            }
        difficulty_experience = {"Easy": 0, "Medium": 0, "Hard": 0, "Expert": 0}
        for question_id in solved_questions:
            if question_id not in self.question_metrics:
                self.calculate_question_difficulty(question_id)
            metrics = self.question_metrics[question_id]
            difficulty_experience[metrics.difficulty_level] += 1
        # 确定总体水平
        if difficulty_experience["Expert"] > 0:
            overall_level = "Expert"
        elif difficulty_experience["Hard"] >= 3:
            overall_level = "Advanced"
        elif difficulty_experience["Medium"] >= 5:
            overall_level = "Intermediate"
        elif difficulty_experience["Easy"] >= 3:
            overall_level = "Beginner"
        else:
            overall_level = "Novice"
        # 识别优势领域
        strength_areas = []
        if difficulty_experience["Expert"] > 0:
            strength_areas.append("Expert-level problem solving")
        if difficulty_experience["Hard"] > 0:
            strength_areas.append("Complex problem analysis")
        if difficulty_experience["Medium"] > 0:
            strength_areas.append("Intermediate problem solving")
        # 识别成长领域
        growth_areas = []
        if difficulty_experience["Easy"] == 0:
            growth_areas.append("Foundation strengthening")
        if difficulty_experience["Medium"] < 3:
            growth_areas.append("Intermediate skill development")
        if difficulty_experience["Hard"] == 0 and overall_level in ["Intermediate", "Advanced"]:
            growth_areas.append("Advanced challenge preparation")
        return {
            "overall_level": overall_level,
            "difficulty_experience": difficulty_experience,
            "strength_areas": strength_areas,
            "growth_areas": growth_areas,
            "total_solved": len(solved_questions)
        }
    def calculate_question_suitability(self, user_level: Dict, question_metrics: QuestionDifficultyMetrics) -> float:
        """
        计算题目对用户的适合度
        Args:
            user_level (Dict): 用户能力水平
            question_metrics (QuestionDifficultyMetrics): 题目指标
        Returns:
            float: 适合度分数 (0-100)
        """
        suitability_score = 0
        # 基于用户水平和题目难度的匹配
        user_overall_level = user_level["overall_level"]
        question_difficulty = question_metrics.difficulty_level
        # 理想匹配得分
        if user_overall_level == "Novice":
            if question_difficulty == "Easy":
                suitability_score += 80
            elif question_difficulty == "Medium":
                suitability_score += 20
        elif user_overall_level == "Beginner":
            if question_difficulty == "Easy":
                suitability_score += 60
            elif question_difficulty == "Medium":
                suitability_score += 90
            elif question_difficulty == "Hard":
                suitability_score += 10
        elif user_overall_level == "Intermediate":
            if question_difficulty == "Easy":
                suitability_score += 20
            elif question_difficulty == "Medium":
                suitability_score += 70
            elif question_difficulty == "Hard":
                suitability_score += 90
            elif question_difficulty == "Expert":
                suitability_score += 30
        elif user_overall_level == "Advanced":
            if question_difficulty == "Medium":
                suitability_score += 30
            elif question_difficulty == "Hard":
                suitability_score += 80
            elif question_difficulty == "Expert":
                suitability_score += 90
        else:  # Expert
            if question_difficulty == "Hard":
                suitability_score += 60
            elif question_difficulty == "Expert":
                suitability_score += 100
        # 基于题目特征的调整
        features = question_metrics.question_features
        # 可接近性调整
        if features["accessibility"] == "High":
            suitability_score += 5
        elif features["accessibility"] == "Low":
            suitability_score -= 10
        # 学习曲线调整
        if features["learning_curve"] == "Gentle" and user_overall_level in ["Novice", "Beginner"]:
            suitability_score += 10
        elif features["learning_curve"] == "Steep" and user_overall_level in ["Advanced", "Expert"]:
            suitability_score += 5
        # 通过率调整（避免过难或过易的题目）
        if 0.2 <= question_metrics.pass_rate <= 0.8:
            suitability_score += 10
        elif question_metrics.pass_rate < 0.1:
            suitability_score -= 20
        elif question_metrics.pass_rate > 0.9:
            suitability_score -= 10
        return max(0, min(100, suitability_score))
    def generate_recommendation_reason(self, user_level: Dict, question: Dict) -> str:
        """
        生成推荐理由
        Args:
            user_level (Dict): 用户能力水平
            question (Dict): 题目信息
        Returns:
            str: 推荐理由
        """
        user_overall_level = user_level["overall_level"]
        question_difficulty = question["difficulty_level"]
        # 基础推荐理由
        if user_overall_level == "Novice" and question_difficulty == "Easy":
            reason = "适合初学者练习基础概念"
        elif user_overall_level == "Beginner" and question_difficulty == "Medium":
            reason = "在掌握基础后，适合提升解题技巧"
        elif user_overall_level == "Intermediate" and question_difficulty == "Hard":
            reason = "挑战高难度题目，提升技术水平"
        elif user_overall_level == "Advanced" and question_difficulty == "Expert":
            reason = "专家级挑战，验证高级技能"
        else:
            reason = "基于您的当前水平量身推荐"
        # 基于题目特征的补充
        features = question["features"]
        if features["learning_curve"] == "Gentle":
            reason += "，学习曲线平缓，易于掌握"
        elif features["accessibility"] == "High":
            reason += "，参与度高，适合练习"
        # 基于通过率的补充
        pass_rate = question["pass_rate"]
        if 0.4 <= pass_rate <= 0.7:
            reason += "，通过率适中，具有挑战性"
        elif pass_rate > 0.7:
            reason += "，通过率较高，适合建立信心"
        return reason
    def get_question_comparison(self, question_ids: List[str]) -> Dict:
        """
        获取题目对比分析
        Args:
            question_ids (List[str]): 题目ID列表
        Returns:
            Dict: 题目对比分析结果
        """
        comparison_data = {
            "questions": [],
            "comparison_metrics": {
                "difficulty_range": None,
                "pass_rate_range": None,
                "complexity_distribution": {},
                "recommendations": []
            }
        }
        difficulty_scores = []
        pass_rates = []
        for question_id in question_ids:
            if question_id not in self.question_metrics:
                self.calculate_question_difficulty(question_id)
            metrics = self.question_metrics[question_id]
            question_data = {
                "question_id": question_id,
                "difficulty_level": metrics.difficulty_level,
                "difficulty_score": round(metrics.difficulty_score, 2),
                "pass_rate": round(metrics.pass_rate * 100, 2),
                "average_attempts": round(metrics.average_attempts, 2),
                "completion_rate": round(metrics.completion_rate * 100, 2),
                "features": metrics.question_features
            }
            comparison_data["questions"].append(question_data)
            difficulty_scores.append(metrics.difficulty_score)
            pass_rates.append(metrics.pass_rate)
        # 计算比较指标
        if difficulty_scores:
            comparison_data["comparison_metrics"]["difficulty_range"] = {
                "min": min(difficulty_scores),
                "max": max(difficulty_scores),
                "avg": statistics.mean(difficulty_scores),
                "std": statistics.stdev(difficulty_scores) if len(difficulty_scores) > 1 else 0
            }
        if pass_rates:
            comparison_data["comparison_metrics"]["pass_rate_range"] = {
                "min": min(pass_rates) * 100,
                "max": max(pass_rates) * 100,
                "avg": statistics.mean(pass_rates) * 100,
                "std": statistics.stdev(pass_rates) * 100 if len(pass_rates) > 1 else 0
            }
        # 复杂度分布
        complexity_dist = {"Low": 0, "Medium": 0, "High": 0}
        for question in comparison_data["questions"]:
            complexity = question["features"]["complexity"]
            if complexity in complexity_dist:
                complexity_dist[complexity] += 1
        comparison_data["comparison_metrics"]["complexity_distribution"] = complexity_dist
        # 生成比较建议
        recommendations = []
        if len(set(difficulty_scores)) == 1:
            recommendations.append("所有题目难度相同，建议增加难度梯度")
        elif max(difficulty_scores) - min(difficulty_scores) > 50:
            recommendations.append("题目难度跨度较大，适合不同水平的用户")
        if statistics.mean(pass_rates) < 0.3:
            recommendations.append("整体通过率较低，建议调整难度或提供更多提示")
        elif statistics.mean(pass_rates) > 0.8:
            recommendations.append("整体通过率较高，可以考虑增加挑战性")
        comparison_data["comparison_metrics"]["recommendations"] = recommendations
        return comparison_data
